﻿using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Text;
using ZT.Core.Model;

namespace ZT.Core.ORM
{
    public class UnitOfWork : IUnitOfWork
    {
        private DbContext cdbContext=null;
        private Dictionary<string, object> repositorys = null;
        public UnitOfWork(PGdb db)
        {
            cdbContext = db;
        }
        /// <summary>
        /// 统一提交数据操作
        /// </summary>
        /// <returns></returns>
        public bool Commit()
        {
            return cdbContext.SaveChanges()>0;
        }

        /// <summary>
        /// 当前请求结束后，会调用该方法，释放当前上下文
        /// </summary>
        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        private void Dispose(bool dispoing)
        {
            if (dispoing)
            {
                if (cdbContext != null)
                {
                    cdbContext.Dispose();
                }
            }
        }

        /// <summary>
        /// 仓储的实例化
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public IRepository<T> Repository<T>() where T : ModelBase
        {
            if (repositorys == null)
            {
                repositorys = new Dictionary<string, object>();
            }
            var type = typeof(T).Name;
            if (!repositorys.ContainsKey(type))
            {
                var repositoryType = typeof(RepositoryPG<>);

                var repository = Activator.CreateInstance(repositoryType.MakeGenericType(typeof(T)), cdbContext);//如果仓储不存在就按创建一个仓储。

                repositorys.Add(type, repository);
            }
            return (RepositoryPG<T>)repositorys[type];
        }
    }
}
